package com.luotat.employeeservice.controller;

import com.luotat.pojo.result.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.luotat.employeeservice.mapper.EmployeeMapper;
import com.luotat.pojo.employee.Employee;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 员工的服务控制层
 */
@AllArgsConstructor
@RestController
@Slf4j
@RequestMapping("/api/employee")
public class EmployeeController
{
    private final EmployeeMapper employeeMapper;

    /**
     * 添加员工
     */
    @PostMapping
    public Result insert(@RequestBody Employee employee)
    {
        try
        {
            employeeMapper.insert(employee);
            log.info("添加员工成功: {}", employee.getName());
            return Result.success("员工添加成功");
        }
        catch (DuplicateKeyException e)
        {
            log.error("员工名已存在: {}", employee.getName(), e);
            return Result.error("员工名已存在");
        }
    }

    /**
     * 删除员工
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id)
    {
        employeeMapper.delete(id);
        log.info("删除员工成功: {}", id);
        return Result.success("删除员工成功");
    }

    // 修改员工
    @PutMapping
    public Result update(@RequestBody Employee employee)
    {
        try
        {
            employeeMapper.update(employee);
            log.info("修改员工成功: {}", employee.getName());
            return Result.success("修改员工成功");
        }
        catch (DuplicateKeyException e)
        {
            log.error("员工名已存在: {}", employee.getName(), e);
            return Result.error("员工名已存在");
        }
    }

    /**
     * 根据id查询员工
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Integer id)
    {
        Employee employee = employeeMapper.getById(id);
        log.info("查询员工成功: {}", employee.getName());
        return Result.success(employee, "查询员工成功");
    }

    /**
     * 查询所有员工
     */
    @GetMapping("/getAll")
    public Result getAll()
    {
        List<Employee> employeeList = employeeMapper.getAll();
        log.info("查询所有员工成功: {}", employeeList.size());
        return Result.success(employeeList, "查询所有员工成功");
    }
}